// Copyright (c) 2023 Huawei Device Co., Ltd.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use std::char;
use std::io::Write;

use serde::ser::{Impossible, Serialize};

use crate::error::*;

pub(crate) fn to_assist_string<T>(value: &T) -> Result<String, XmlError>
where
    T: ?Sized + Serialize,
{
    let mut writer = Vec::with_capacity(128);
    value.serialize(&mut AssistStringSerializer::new(&mut writer))?;
    Ok(String::from_utf8(writer)?)
}

struct AssistStringSerializer<W: Write> {
    writer: W,
}

impl<W: Write> AssistStringSerializer<W> {
    fn new(writer: W) -> Self {
        AssistStringSerializer { writer }
    }
}

impl<'ser, W: 'ser + Write> serde::ser::Serializer for &'ser mut AssistStringSerializer<W> {
    type Ok = ();
    type Error = XmlError;

    type SerializeSeq = Impossible<Self::Ok, Self::Error>;
    type SerializeMap = Impossible<Self::Ok, Self::Error>;
    type SerializeStruct = Impossible<Self::Ok, Self::Error>;
    type SerializeStructVariant = Impossible<Self::Ok, Self::Error>;
    type SerializeTuple = Impossible<Self::Ok, Self::Error>;
    type SerializeTupleStruct = Impossible<Self::Ok, Self::Error>;
    type SerializeTupleVariant = Impossible<Self::Ok, Self::Error>;

    fn serialize_bool(self, v: bool) -> Result<Self::Ok, Self::Error> {
        self.writer.write_fmt(format_args!("{v}"))?;
        Ok(())
    }

    fn serialize_i8(self, v: i8) -> Result<Self::Ok, Self::Error> {
        self.serialize_i64(i64::from(v))
    }

    fn serialize_i16(self, v: i16) -> Result<Self::Ok, Self::Error> {
        self.serialize_i64(i64::from(v))
    }

    fn serialize_i32(self, v: i32) -> Result<Self::Ok, Self::Error> {
        self.serialize_i64(i64::from(v))
    }

    fn serialize_i64(self, v: i64) -> Result<Self::Ok, Self::Error> {
        self.writer.write_fmt(format_args!("{v}"))?;
        Ok(())
    }

    fn serialize_u8(self, v: u8) -> Result<Self::Ok, Self::Error> {
        self.serialize_u64(u64::from(v))
    }

    fn serialize_u16(self, v: u16) -> Result<Self::Ok, Self::Error> {
        self.serialize_u64(u64::from(v))
    }

    fn serialize_u32(self, v: u32) -> Result<Self::Ok, Self::Error> {
        self.serialize_u64(u64::from(v))
    }

    fn serialize_u64(self, v: u64) -> Result<Self::Ok, Self::Error> {
        self.writer.write_fmt(format_args!("{v}"))?;
        Ok(())
    }

    fn serialize_f32(self, v: f32) -> Result<Self::Ok, Self::Error> {
        self.serialize_f64(f64::from(v))
    }

    fn serialize_f64(self, v: f64) -> Result<Self::Ok, Self::Error> {
        self.writer.write_fmt(format_args!("{v}"))?;
        Ok(())
    }

    fn serialize_char(self, v: char) -> Result<Self::Ok, Self::Error> {
        self.writer.write_fmt(format_args!("{v}"))?;
        Ok(())
    }

    fn serialize_str(self, v: &str) -> Result<Self::Ok, Self::Error> {
        self.writer.write_fmt(format_args!("{v}"))?;
        Ok(())
    }

    fn serialize_bytes(self, _v: &[u8]) -> Result<Self::Ok, Self::Error> {
        Err(XmlError::from(OtherError::Transform))
    }

    fn serialize_none(self) -> Result<Self::Ok, Self::Error> {
        Err(XmlError::from(OtherError::Transform))
    }

    fn serialize_some<T: ?Sized>(self, _value: &T) -> Result<Self::Ok, Self::Error>
    where
        T: Serialize,
    {
        Err(XmlError::from(OtherError::Transform))
    }

    fn serialize_unit(self) -> Result<Self::Ok, Self::Error> {
        Err(XmlError::from(OtherError::Transform))
    }

    fn serialize_unit_struct(self, _name: &'static str) -> Result<Self::Ok, Self::Error> {
        Err(XmlError::from(OtherError::Transform))
    }

    fn serialize_unit_variant(
        self,
        _name: &'static str,
        _variant_index: u32,
        _variant: &'static str,
    ) -> Result<Self::Ok, Self::Error> {
        Err(XmlError::from(OtherError::Transform))
    }

    fn serialize_newtype_struct<T: ?Sized>(
        self,
        _name: &'static str,
        _value: &T,
    ) -> Result<Self::Ok, Self::Error>
    where
        T: Serialize,
    {
        Err(XmlError::from(OtherError::Transform))
    }

    fn serialize_newtype_variant<T: ?Sized>(
        self,
        _name: &'static str,
        _variant_index: u32,
        _variant: &'static str,
        _value: &T,
    ) -> Result<Self::Ok, Self::Error>
    where
        T: Serialize,
    {
        Err(XmlError::from(OtherError::Transform))
    }

    fn serialize_seq(self, _len: Option<usize>) -> Result<Self::SerializeSeq, XmlError> {
        Err(XmlError::from(OtherError::Transform))
    }

    fn serialize_tuple(self, _len: usize) -> Result<Self::SerializeTuple, XmlError> {
        Err(XmlError::from(OtherError::Transform))
    }

    fn serialize_tuple_struct(
        self,
        _name: &'static str,
        _len: usize,
    ) -> Result<Self::SerializeTupleStruct, XmlError> {
        Err(XmlError::from(OtherError::Transform))
    }

    fn serialize_tuple_variant(
        self,
        _name: &'static str,
        _variant_index: u32,
        _variant: &'static str,
        _len: usize,
    ) -> Result<Self::SerializeTupleVariant, XmlError> {
        Err(XmlError::from(OtherError::Transform))
    }

    fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap, XmlError> {
        Err(XmlError::from(OtherError::Transform))
    }

    fn serialize_struct(
        self,
        _name: &'static str,
        _len: usize,
    ) -> Result<Self::SerializeStruct, XmlError> {
        Err(XmlError::from(OtherError::Transform))
    }

    fn serialize_struct_variant(
        self,
        _name: &'static str,
        _variant_index: u32,
        _variant: &'static str,
        _len: usize,
    ) -> Result<Self::SerializeStructVariant, XmlError> {
        Err(XmlError::from(OtherError::Transform))
    }
}

#[cfg(test)]
mod ut_assist_string {
    use crate::assist_string::*;
    use serde::Serialize;
    use std::collections::HashMap;

    /// UT test for AssistStringSerializer.
    ///
    /// # Title
    /// ut_assist_string_serializer
    ///
    /// # Brief
    /// 1.Uses `to_assist_string` method to serialize some types.
    /// 2.Checks if the test results are correct.
    #[test]
    fn ut_assist_string_serializer() {
        let value: Option<u32> = None;
        assert!(to_assist_string(&value).is_err());

        let value: Option<u32> = Some(123);
        assert!(to_assist_string(&value).is_err());

        let value = true;
        assert!(to_assist_string(&value).is_ok());

        let value: i8 = 123;
        assert!(to_assist_string(&value).is_ok());

        let value: i16 = 123;
        assert!(to_assist_string(&value).is_ok());

        let value: i32 = 123;
        assert!(to_assist_string(&value).is_ok());

        let value: i64 = 123;
        assert!(to_assist_string(&value).is_ok());

        let value: u8 = 123;
        assert!(to_assist_string(&value).is_ok());

        let value: u16 = 123;
        assert!(to_assist_string(&value).is_ok());

        let value: u32 = 123;
        assert!(to_assist_string(&value).is_ok());

        let value: u64 = 123;
        assert!(to_assist_string(&value).is_ok());

        let value: f32 = 1.0;
        assert!(to_assist_string(&value).is_ok());

        let value: f64 = 1.0;
        assert!(to_assist_string(&value).is_ok());

        let value = 't';
        assert!(to_assist_string(&value).is_ok());

        let value = "abc";
        assert!(to_assist_string(&value).is_ok());

        let value = b"abc";
        assert!(to_assist_string(&value).is_err());

        #[derive(Serialize)]
        struct TestUnit;
        let value = TestUnit;
        assert!(to_assist_string(&value).is_err());

        #[derive(Serialize)]
        struct TestNewtype(u32);
        let value = TestNewtype(123);
        assert!(to_assist_string(&value).is_err());

        #[derive(Serialize)]
        struct TestTuple(u32, u32, bool);
        let value = TestTuple(123, 321, true);
        assert!(to_assist_string(&value).is_err());

        #[derive(Serialize)]
        struct Test {
            int: u32,
            seq: Vec<&'static str>,
            tup: (i32, i32, i32),
        }

        let value = Test {
            int: 1,
            seq: vec!["a", "b"],
            tup: (1, 2, 3),
        };
        assert!(to_assist_string(&value).is_err());

        #[derive(Serialize)]
        enum E {
            Newtype(i32),
            Unit,
            Struct { a: u32 },
            Tuple(u32, u32),
        }

        let value = E::Newtype(-1);
        assert!(to_assist_string(&value).is_err());

        let value = E::Unit;
        assert!(to_assist_string(&value).is_err());

        let value = E::Struct { a: 10 };
        assert!(to_assist_string(&value).is_err());

        let value = E::Tuple(100, 200);
        assert!(to_assist_string(&value).is_err());

        let mut hash = HashMap::new();
        hash.insert("apple", 1);
        assert!(to_assist_string(&hash).is_err());
    }
}
